// *************************************
// * Creator:SunnyPaine
// * DateTime:2024/09/04 09:09:18
// * Description:<Description>
// * CopyRight:
// * ***********************************

using Autofac;
using SunnyPaine.Autofac.Extension.Stereotype;
using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;

namespace SunnyPaine.Autofac.Extension.Mvvm.ViewCore
{
    /// <summary>
    /// 表示视图指定区域的组件。
    /// </summary>
    public static class RegionComponent
    {
        /// <summary>
        /// 视图指定区域的名称。
        /// </summary>
        public static readonly DependencyProperty RegionNameProperty =
            DependencyProperty.RegisterAttached("RegionName", typeof(string), typeof(RegionComponent),
                new PropertyMetadata(OnSetRegionNameCallback));

        private static void OnSetRegionNameCallback(DependencyObject element, DependencyPropertyChangedEventArgs args)
        {
            if (!DesignerProperties.GetIsInDesignMode(element))
            {
                string regionName = args.NewValue.ToString();
                ContentControl control = element as ContentControl;
                if (control == null)
                {
                    throw new InvalidOperationException($"RegionName={regionName} 指向的组件类型必须为 {typeof(ContentControl).FullName}");
                }

                IControl viewControl = ServiceLocator.Container.Resolve<IViewContext>().ResolveControl(regionName);
                control.Content = viewControl;
            }
        }
    }
}